package com.example.spring_security.config;

import com.example.spring_security.callback.FailureHandler;
import com.example.spring_security.callback.SuccessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

/**
 * @Description 自定义 表单登录
 * @Author lihw
 * @Date 2024/5/29 8:52
 */
// @Configuration
// @EnableWebSecurity
public class SecurityConfig4 {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests((authorize) -> authorize
                        .requestMatchers("/login").permitAll()
                        .anyRequest().authenticated()
                )
                .formLogin(form -> form
                        // 前端表单登录用户名别名
                        .usernameParameter("username")
                        // 前端表单登录密码别名
                        .passwordParameter("password")
                        .loginPage("/login")
                        .successHandler(new SuccessHandler())
                        .failureHandler(new FailureHandler())
                )
               ;

        return http.build();
    }

    // @Bean
    // public UserDetailsService userDetailsService() {
    //     UserDetails userDetails = User.withDefaultPasswordEncoder()
    //             .username("lhw")
    //             .password("123456")
    //             .roles("NORMAL")
    //             .build();
    //
    //     return new InMemoryUserDetailsManager(userDetails);
    // }
    @Bean
    public UserDetailsService users() {
        // The builder will ensure the passwords are encoded before saving in memory
        User.UserBuilder users = User.withDefaultPasswordEncoder();
        UserDetails user = users
                .username("lhw")
                .password("123456")
                .roles("NORMAL")
                .build();
        UserDetails admin = users
                .username("admin")
                .password("password")
                .roles("USER", "ADMIN")
                .build();
        return new InMemoryUserDetailsManager(user, admin);
    }

}
